package cn.zhentao.controller;

import cn.zhentao.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/vip")
public class PayController {
    @Autowired
    private AlipayService alipayService;

    /**
     * 创建支付宝支付订单，返回支付宝收银台的 HTML 表单
     * 入参：{ orderNo, amount, vipType }
     * 返回：{ code, message, data: { formHtml } }
     */
    @PostMapping("/pay/alipay/create")
    public Map<String, Object> createOrder(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            String orderNo = params.get("orderNo").toString();
            BigDecimal amount = new BigDecimal(params.get("amount").toString());
            String vipType = params.get("vipType") != null ? params.get("vipType").toString() : ("订单支付-" + orderNo);

            // 要求必须提供 userId，避免匿名订单；兼容前端仅传 id 的情况
            Object userIdObj = params.get("userId");
            if (userIdObj == null && params.get("id") != null) {
                userIdObj = params.get("id");
            }
            if (userIdObj == null) {
                Map<String, Object> err = new HashMap<>();
                err.put("code", 400);
                err.put("message", "缺少用户信息：userId 为空（可传 userId 或 id），无法创建支付订单");
                return err;
            }

            // 组装 passback_params：把前端已登录用户信息与套餐信息透传，回调时用于建单/关联用户
            Map<String, Object> passback = new HashMap<>();
            passback.put("userId", userIdObj);
            if (params.get("username") != null) passback.put("username", params.get("username"));
            if (params.get("nickname") != null) passback.put("nickname", params.get("nickname"));
            if (params.get("packageId") != null) passback.put("packageId", params.get("packageId"));
            if (params.get("vipType") != null) passback.put("vipType", params.get("vipType"));
            if (params.get("amount") != null) passback.put("amount", params.get("amount"));
            if (params.get("duration") != null) passback.put("duration", params.get("duration"));

            String payUrl = alipayService.createAlipayOrder(orderNo, amount, vipType, passback);

            result.put("code", 200);
            result.put("message", "创建订单成功");
            Map<String, Object> data = new HashMap<>();
            data.put("url", payUrl);
            result.put("data", data);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "创建订单失败：" + e.getMessage());
        }
        return result;
    }


}
